//
//  FRPPhotoImporter.m
//  FunctionalReactivePixels
//
//  Created by sun on 15/7/1.
//  Copyright (c) 2015年 sunfei. All rights reserved.
//

#import "FRPPhotoImporter.h"
#import "FRPPhotoModel.h"

@implementation FRPPhotoImporter

//+ (RACSignal *)importPhotos {
//    RACReplaySubject *subject = [RACReplaySubject subject];
//    NSURLRequest *request = [self popularURLRequest];
//    
//    NSURLSession *session = [NSURLSession sharedSession];
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//        if (httpResponse.statusCode == 200) {
//            if (data) {
//                id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                [subject sendNext:[[[results[@"photos"] rac_sequence]
//                                   map:^id(NSDictionary *photoDictionary) {
//                                       FRPPhotoModel *model = [FRPPhotoModel new];
//                                       [self configurePhotoModel:model withDictionary:photoDictionary];
//                                       [self downloadThumbnailForPhotoModel:model];
//                                       return model;
//                                   }] array]];
//                [subject sendCompleted];
//            } else {
//                [subject sendError:error];
//            }
//        } else {
//            [subject sendError:error];
//        }
//    }] resume];
//    return subject;
//}

+ (RACSignal *)importPhotos {
    NSURLRequest *request = [self popularURLRequest];
    return [[[[[[NSURLConnection rac_sendAsynchronousRequest:request] reduceEach:^id(NSURLResponse *response, NSData *data){
        return data;
    }] deliverOn:[RACScheduler mainThreadScheduler]] map:^id(NSData *data) {
        id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        return [[[results[@"photos"] rac_sequence] map:^id(NSDictionary *photoDictionary) {
            FRPPhotoModel *model = [FRPPhotoModel new];
            [self configurePhotoModel:model withDictionary:photoDictionary];
            [self downloadThumbnailForPhotoModel:model];
            return model;
        }] array];
    }] publish] autoconnect];
}

+ (NSURLRequest *)popularURLRequest {
    return [[PXRequest apiHelper] urlRequestForPhotoFeature:PXAPIHelperPhotoFeaturePopular
                                                resultsPerPage:100
                                                          page:0
                                                    photoSizes:PXPhotoModelSizeThumbnail
                                                     sortOrder:PXAPIHelperSortOrderRating
                                                        except:PXPhotoModelCategoryNude];
    
}

+ (void)configurePhotoModel:(FRPPhotoModel *)model withDictionary:(NSDictionary *)dic {
    model.photoName = dic[@"name"];
    model.identifier = dic[@"id"];
    model.photographerName = dic[@"user"][@"username"];
    model.rating = dic[@"rating"];
    model.thumbnailURL = [self urlForImageSize:3 inArray:dic[@"images"]];
    
    if (dic[@"comments_count"]) {
        model.fullsizedURL = [self urlForImageSize:4 inArray:dic[@"images"]];
    }
}

+ (void)downloadThumbnailForPhotoModel:(FRPPhotoModel *)model {
//    NSAssert(model.thumbnailURL, @"thumbailURL must not nil");
//    
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.thumbnailURL]];
//    NSURLSession *session = [NSURLSession sharedSession];
//    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//        if (httpResponse.statusCode == 200) {
//            model.thumbnailData = data;
//        }
//    }] resume];
    
//    [self download:model.thumbnailURL withCompletion:^(NSData *data) {
//        model.thumbnailData = data;
//    }];
    
    RAC(model, thumbnailData) = [self download:model.thumbnailURL];
}

+ (void)downloadFullsizedImageForPhotoModel:(FRPPhotoModel *)model {
//    [self download:model.fullsizedURL withCompletion:^(NSData *data) {
//        model.fullsizedData = data;
//    }];
    RAC(model, fullsizedData) = [self download:model.fullsizedURL];
}

+ (NSString *)urlForImageSize:(NSInteger)size inArray:(NSArray *)array {
    return [[[[[array rac_sequence] filter:^BOOL(NSDictionary *value) {
        return [value[@"size"] integerValue] == size;
    }] map:^id(id value) {
        return value[@"url"];
    }] array] firstObject];
}

//+ (RACSignal *)fetchPhotoDetails:(FRPPhotoModel *)model {
//    RACReplaySubject *subject = [RACReplaySubject subject];
//    NSURLRequest *request = [self photoURLRequest:model];
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//    NSURLSession *session = [NSURLSession sharedSession];
//    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//            if (httpResponse.statusCode == 200 && data) {
//                id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil][@"photo"];
//                [self configurePhotoModel:model withDictionary:results];
//                [self downloadFullsizedImageForPhotoModel:model];
//                [subject sendNext:model];
//                [subject sendCompleted];
//            } else {
//                [subject sendError:error];
//            }
//        });
//    }] resume];
//    return subject;
//}

+ (RACSignal *)fetchPhotoDetails:(FRPPhotoModel *)model {
    NSURLRequest *request = [self photoURLRequest:model];
    return [[[[[[NSURLConnection rac_sendAsynchronousRequest:request] map:^id(RACTuple *value) {
        return value.second;
    }] deliverOn:[RACScheduler mainThreadScheduler]] map:^id(NSData *data) {
        id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil][@"photo"];
        [self configurePhotoModel:model withDictionary:results];
        [self downloadFullsizedImageForPhotoModel:model];
        return model;
    }] publish] autoconnect];
}

+ (NSURLRequest *)photoURLRequest:(FRPPhotoModel *)photoModel {
    return [[PXRequest apiHelper] urlRequestForPhotoID:photoModel.identifier.integerValue];
}

//+ (void)download:(NSString *)urlString withCompletion:(void(^)(NSData *data))completion {
//    NSAssert(urlString, @"URL must not be nil");
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//    NSURLSession *session = [NSURLSession sharedSession];
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//           [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//            if (httpResponse.statusCode == 200 && data && completion) {
//                completion(data);
//            }
//        });
//    }] resume];
//}

+ (RACSignal *)download:(NSString *)urlString {
    NSAssert(urlString, @"must be not nil");
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    return [[[NSURLConnection rac_sendAsynchronousRequest:request] map:^id(RACTuple *value) {
        return [value second];
    }] deliverOn:[RACScheduler mainThreadScheduler]];
}

@end
